<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 新闻管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="primary"
          icon="el-icon-delete"
          class="handle-del mr10"
          @click="delAllSelection"
        >批量删除
        </el-button>
        <el-cascader
          v-model="selectCate"
          placeholder="筛选类别"
          :props="{ expandTrigger: 'hover' }"
          :options="options"></el-cascader>  <!--@change="handleChange"  绑定值改变时的事件-->
        <el-input v-model="selectWord" placeholder="筛选关键词" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="getData">刷新</el-button>
      </div>
      <el-table
        :data="data"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >

        <el-table-column type="selection" width="55" align="center"></el-table-column>

        <el-table-column type="index" :index="indexMethod" label="ID" width="55" align="center"></el-table-column>

        <el-table-column prop="btitle" width="200" label="大标题"></el-table-column>

        <el-table-column prop="ltitle" width="200" label="小标题"></el-table-column>

        <el-table-column prop="content" width="300" label="新闻内容"></el-table-column>

        <el-table-column prop="category" width="100" label="类别" align="center"></el-table-column>

        <el-table-column prop="author" width="100" label="发布人" align="center"></el-table-column>

        <el-table-column width="160" label="发布时间">
          <template slot-scope="scope">
            {{ scope.row.time.substring(0,10)+" "+scope.row.time.substring(11,19) }}
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.state==='通过'?'success':(scope.row.state==='失败'?'danger':'')">
              {{scope.row.state}}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              v-show=" scope.row.state === '待审核'|| scope.row.state === '失败' "
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >修改<!-- scope.$index  获取表格里面当前数据的编号  每页的编号都是0 到  9   -->
            </el-button>
            <el-button
              type="text"
              icon="el-icon-tickets"
              @click=""
            >预览
            </el-button>
            <el-button
              type="text"
              icon="el-icon-top"
              @click=""
            >置顶
            </el-button>
            <el-button
              type="text"
              icon="el-icon-star-on"
              @click=""
            >热门
            </el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>


      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="page.index"
          :page-size="page.size"
          :total="page.total"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>


    <!-- 修改弹出框 -->

    <el-dialog title="修改" :visible.sync="editVisible" width="50%">
      <el-form ref="form" :model="form" label-width="70px">
        <el-form-item label="大标题">
          <el-input v-model="form.btitle" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="小标题">
          <el-input v-model="form.ltitle"></el-input>
        </el-form-item>
        <el-form-item label="类别选择">
          <el-select v-model="form.category" placeholder="请选择">
            <el-option key="bbk" label="步步高" value="bbk"></el-option>
            <el-option key="xtc" label="小天才" value="xtc"></el-option>
            <el-option key="imoo" label="imoo" value="imoo"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容概括">
          <el-input type="textarea" rows="3" v-model="form.introduction"></el-input>
        </el-form-item>
        <el-form-item label="新闻内容" style="width: 900px">
          <mavon-editor v-model="form.content" ref="md" @imgAdd="$imgAdd" @change="change" style="min-height: 600px"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit(form)">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>
<script>
  import {mavonEditor} from 'mavon-editor'
  import 'mavon-editor/dist/css/index.css'

  export default {
    name: 'basetable',
    components: {
      mavonEditor
    },
    data() {
      return {
        tableData: [],//表格数据
        multipleSelection: [],
        delList: [],//多选后需要删除的列表
        delId: '',//删除操作的id
        selectCate: '',//搜索类别
        selectWord: '',//搜索关键词
        editVisible: false,//修改页面是否显示
        datas: 0,
        selectdata: '',//搜索后的表格数据
        time: '',
        page: {//分页数据
          index: 1,//初始页
          size: 10,//每页数量
          total: 0,//总数据量
          num: 0,//分页后的数据量  需要赋给total
        },
        form: {},
        idx: -1,
        id: -1,
        options: [
          {
          value: 'zhinan',
          label: '指南',
          children: [{
            value: 'shejiyuanze',
            label: '设计原则',
            children: [{
              value: 'yizhi',
              label: '一致'
            }, {
              value: 'fankui',
              label: '反馈'
            }, {
              value: 'xiaolv',
              label: '效率'
            }, {
              value: 'kekong',
              label: '可控'
            }]
          }, {
            value: 'daohang',
            label: '导航',
            children: [{
              value: 'cexiangdaohang',
              label: '侧向导航'
            }, {
              value: 'dingbudaohang',
              label: '顶部导航'
            }]
          }]
        }, {
          value: 'zujian',
          label: '组件',
          children: [{
            value: 'basic',
            label: 'Basic',
            children: [{
              value: 'layout',
              label: 'Layout 布局'
            }, {
              value: 'color',
              label: 'Color 色彩'
            }, {
              value: 'typography',
              label: 'Typography 字体'
            }, {
              value: 'icon',
              label: 'Icon 图标'
            }, {
              value: 'button',
              label: 'Button 按钮'
            }]
          }, {
            value: 'form',
            label: 'Form',
            children: [{
              value: 'radio',
              label: 'Radio 单选框'
            }, {
              value: 'checkbox',
              label: 'Checkbox 多选框'
            }, {
              value: 'input',
              label: 'Input 输入框'
            }, {
              value: 'input-number',
              label: 'InputNumber 计数器'
            }, {
              value: 'select',
              label: 'Select 选择器'
            }, {
              value: 'cascader',
              label: 'Cascader 级联选择器'
            }, {
              value: 'switch',
              label: 'Switch 开关'
            }, {
              value: 'slider',
              label: 'Slider 滑块'
            }, {
              value: 'time-picker',
              label: 'TimePicker 时间选择器'
            }, {
              value: 'date-picker',
              label: 'DatePicker 日期选择器'
            }, {
              value: 'datetime-picker',
              label: 'DateTimePicker 日期时间选择器'
            }, {
              value: 'upload',
              label: 'Upload 上传'
            }, {
              value: 'rate',
              label: 'Rate 评分'
            }, {
              value: 'form',
              label: 'Form 表单'
            }]
          }, {
            value: 'data',
            label: 'Data',
            children: [{
              value: 'table',
              label: 'Table 表格'
            }, {
              value: 'tag',
              label: 'Tag 标签'
            }, {
              value: 'progress',
              label: 'Progress 进度条'
            }, {
              value: 'tree',
              label: 'Tree 树形控件'
            }, {
              value: 'pagination',
              label: 'Pagination 分页'
            }, {
              value: 'badge',
              label: 'Badge 标记'
            }]
          }, {
            value: 'notice',
            label: 'Notice',
            children: [{
              value: 'alert',
              label: 'Alert 警告'
            }, {
              value: 'loading',
              label: 'Loading 加载'
            }, {
              value: 'message',
              label: 'Message 消息提示'
            }, {
              value: 'message-box',
              label: 'MessageBox 弹框'
            }, {
              value: 'notification',
              label: 'Notification 通知'
            }]
          }, {
            value: 'navigation',
            label: 'Navigation',
            children: [{
              value: 'menu',
              label: 'NavMenu 导航菜单'
            }, {
              value: 'tabs',
              label: 'Tabs 标签页'
            }, {
              value: 'breadcrumb',
              label: 'Breadcrumb 面包屑'
            }, {
              value: 'dropdown',
              label: 'Dropdown 下拉菜单'
            }, {
              value: 'steps',
              label: 'Steps 步骤条'
            }]
          }, {
            value: 'others',
            label: 'Others',
            children: [{
              value: 'dialog',
              label: 'Dialog 对话框'
            }, {
              value: 'tooltip',
              label: 'Tooltip 文字提示'
            }, {
              value: 'popover',
              label: 'Popover 弹出框'
            }, {
              value: 'card',
              label: 'Card 卡片'
            }, {
              value: 'carousel',
              label: 'Carousel 走马灯'
            }, {
              value: 'collapse',
              label: 'Collapse 折叠面板'
            }]
          }]
        }, {
          value: 'ziyuan',
          label: '资源',
          children: [{
            value: 'axure',
            label: 'Axure Components'
          }, {
            value: 'sketch',
            label: 'Sketch Templates'
          }, {
            value: 'jiaohu',
            label: '组件交互文档'
          }]
        }]
      };
    },
    watch: {
      selectWord(newval) {
        if (newval && newval != '') {
          this.datas = 1;
          this.selectWord = newval;
        } else {
          this.datas = 0;
        }
      }
    },
    created() {
      this.getData();
    },
    computed: {
      data() {
        if (this.datas === 0) {
          this.page.total = this.page.num;
          return this.tableData
        } else if (this.datas === 1) {
          let item = new Array();
          this.page.total = 0;
          this.selectdata.filter(res => {
            if (res.author.includes(this.selectWord) || res.btitle.includes(this.selectWord)) {
              this.page.total++;
              item.push(res);
            }
          });
          let newItem = new Array(10);
          for (let i = (this.page.index - 1) * 10; i < this.page.index * 10; i++) {
            if (item[i] && item[i] != '') {
              newItem.push(item[i]);
            } else {
              break;
            }
          }
          return newItem;
        }
      }
    },
    methods: {
      $imgAdd(pos, $file) {
        var formdata = new FormData();
        formdata.append('file', $file);
        // 这里没有服务器供大家尝试，可将下面上传接口替换为你自己的服务器接口
        this.$axios({
          url: '/common/upload',
          method: 'post',
          data: formdata,
          headers: {'Content-Type': 'multipart/form-data'},
        }).then((url) => {
          this.$refs.md.$img2Url(pos, url);
        })
      },
      change(value, render) {
        // render 为 markdown 解析后的结果
        this.html = render;
      },

      // 获取数据
      getData() {
        var that = this;

        let url = 'http://localhost:9999/news/getpage?pageNum=' + this.page.index + '&pageSize=' + this.page.size;
        //  当发起get请求之后， 通过 .then 来设置成功的回调函数
        this.$http.get(url).then(function (result) {
          // 通过 result.body 拿到服务器返回的成功的数据
          that.tableData = result.body;
          // console.log(that.tableData);
        });

        let url1 = 'http://localhost:9999/news/getAll';
        //  当发起get请求之后， 通过 .then 来设置成功的回调函数
        this.$http.get(url1).then(function (result) {
          // 通过 result.body 拿到服务器返回的成功的数据
          that.page.num = result.body.length;
          that.selectdata = result.body;
        })

      },
      // 触发搜索按钮
      handleSearch() {
      },
      // 删除操作
      handleDelete(row) {
        // let that = this;
        // 二次确认删除
        this.$confirm('确定要删除吗？', '提示', {
          type: 'warning'
        })
          .then(() => {
            //发送删除命令

            let url = 'http://localhost:9999/news/deleteById?id=' + row.id;
            // console.log(url);
            //  当发起post请求之后， 通过 .then 来设置成功的回调函数
            this.$http.get(url).then(result => {
              if (result.body === 1) {
                this.getData();
                this.$message.success('删除成功');
              } else {
                this.$message.error('删除失败,请联系管理员进行删除');
              }
              // console.log(result);
            }, response => {
              this.$message.error('删除失败，数据库连接错误');
              // error callback
            });

            // this.tableData.splice(index, 1);
          })
          .catch(() => {
          });
      },
      // 多选操作
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      delAllSelection() {
        const length = this.multipleSelection.length;
        let str = '';
        this.delList = this.delList.concat(this.multipleSelection);
        for (let i = 0; i < length; i++) {
          str += this.multipleSelection[i].id + ' ';
        }
        this.$message.error(`删除了${str}`);
        this.multipleSelection = [];
      },
      // 编辑操作
      handleEdit(row) {
        // console.log(row);
        // this.idx = index+1+(this.page.index-1)*10 ;//第idx条数据
        // this.id = row.id;
        this.form = row;
        this.editVisible = true;
      },
      // 保存编辑
      saveEdit(form) {
        this.editVisible = false;
        console.log(form);
        let url = 'http://localhost:9999/news/updateNews';
        // console.log(url);
        //  当发起post请求之后， 通过 .then 来设置成功的回调函数
        this.$http.post(url, form).then(result => {
          // console.log(result);
        }, response => {
          // error callback
        });


        // this.$set(this.tableData, this.idx, this.form);//前端数据修改  数据库没变
        this.$message.success(`修改成功`);
        // this.$message.success(`修改第 ${this.idx} 行成功`);
      },
      // 分页导航
      handlePageChange(val) {
        this.page.index = val;
        this.getData();
      },
      indexMethod(index) {
        return index + 1 + (this.page.index - 1) * 10;
      }
    }
  };
</script>

<style scoped>
  .handle-box {
    margin-bottom: 20px;
  }

  .handle-select {
    width: 120px;
  }

  .handle-input {
    width: 300px;
    display: inline-block;
  }

  .table {
    width: 100%;
    font-size: 14px;
  }

  .red {
    color: #ff0000;
  }

  .mr10 {
    margin-right: 10px;
  }

  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }
</style>
